
### -------------------------------------------------- ###
### ---- 1) Function: Add State Flags for Ea. Var ---- 
### -------------------------------------------------- ###

fun_state_variable_flag <- function(dat, ABB, choose_var){
  
  # Require necessary functions
  require(lazyeval)
  require(dplyr)
  
  # Call V: Mark as 1 if variable called choose_var equals chosen state (ABB)
  mutate_call_v <- lazyeval::interp(~ ifelse(var_name==ABB & !is.na(var_name) & !var_name==0, 1, 0), #rhs of = in mutate()
                                    var_name = as.name(choose_var)) #name of var in above expression (can use paste0() in name)
  # Run mutate for Call V  
  dat %<>% mutate_(.dots = setNames(list(mutate_call_v), paste0(choose_var,"_",ABB)))  
  
  return(dat)
  
}


### -------------------------------------------------- ###
### ---- 2) Function: Add State Flags w. Total ---- 
### -------------------------------------------------- ###


fun_state_flag <- function(dat, ABB){
  
  # Require necessary functions
  require(lazyeval)
  require(dplyr)
  
  # Call T: total state id variables that equal chosen state (ABB)
  mutate_call_t <- lazyeval::interp( ~ v1 + v2 + v3 + v4 + v5, 
                                     v1 = as.name(paste0("state_ca_",ABB)), 
                                     v2 = as.name(paste0("state_uni_",ABB)), 
                                     v3 = as.name(paste0("state_st_",ABB)), 
                                     v4 = as.name(paste0("state_mr_",ABB)),
                                     v5 = as.name(paste0("state_cell_",ABB)) )
  # Run mutate for Call T  
  dat %<>% mutate_(.dots = setNames(list(mutate_call_t), paste0("state_",ABB,"_total"))) 
  
  # Call F: Mark as 1 if even one state id variable equals chosen state (ABB)
  mutate_call_f <- lazyeval::interp( ~ ifelse(var_total>0, 1, 0), #rhs of = in mutate()
                                     var_total = as.name(paste0("state_",ABB,"_total")) ) #name of var in above expression 
  # Run mutate for Call F  
  dat %<>% mutate_(.dots = setNames(list(mutate_call_f), paste0("state_",ABB,"_flag"))) 
  
  return(dat)
}




